package com.ctrip.ec.api.mobile.controller;

import com.ctrip.ec.api.mobile.common.RequestContext;
import com.ctrip.ec.api.mobile.common.ValidateException;
import com.ctrip.ec.api.mobile.model.after.AfterSalesModel;
import com.ctrip.ec.biz.dao.after.AfterSalesDao;
import com.ctrip.ec.biz.dao.order.OrderDao;
import com.ctrip.ec.biz.dao.order.OrderGoodsDao;
import com.ctrip.ec.biz.dao.store.StoreDao;
import com.ctrip.ec.biz.entity.after.AfterSalesEntity;
import com.ctrip.ec.biz.entity.after.AfterSalesStatus;
import com.ctrip.ec.biz.entity.after.AfterSalesType;
import com.ctrip.ec.biz.entity.order.OrderEntity;
import com.ctrip.ec.biz.entity.order.OrderGoodsEntity;
import com.ctrip.ec.biz.entity.order.OrderStatus;
import com.ctrip.ec.biz.entity.store.StoreEntity;
import com.ctrip.ec.dal.PagerSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by jiangzy on 2018/11/28.
 */
@RestController
@RequestMapping("afterSales")
public class AfterSalesController {

    /*
    1、售后可以申请多次（分 退货/退款 、换货），但同一时间内同一商品只能有一个售后，审核完成之前不得再有申请
    2、退款条件 ：订单状态只要支付成功后关闭前都可以（即，订单状态在1、2可申请退款，0、3 、-1不能申请退款）
    3、多次退款条件：在订单商品表里有一个字段backNum表示退款个数，一旦达到购买数buyNum后不能再次申请退款。
    4、换货条件：订单状态为已发货（即订单状态为2），其余状态不能换货
    5、一个商品是否在售后中，根据订单商品表里的inAfterSales来进行判断
    6、订单商品表里afterSalseType：0未申请售后，1退货，2换货（如果有多次，表示最后一次的类型）
    7、订单商品表里afterSalseStatus: 0未申请售后，1待审核 2审核过 3拒绝（如果有多次，表示最后一次的状态）

     */

    @Autowired
    private OrderDao order;

    @Autowired
    private OrderGoodsDao orderGoods;

    @Autowired
    private AfterSalesDao afterSales;

    @Autowired
    private StoreDao store;


    @Value("${imageDomain}")
    private String imageDomain;


    @PostMapping("save")
    public void save(@RequestBody AfterSalesEntity entity) throws SQLException {
        OrderGoodsEntity orderGoodsEntity = orderGoods.entity(entity.getOrderGoodsId());
        OrderEntity orderEntity = order.entity(orderGoodsEntity.getOrderId());
        if (orderGoodsEntity.getInAfterSales()) {
            throw new ValidateException("本商品您有一个售后单，请结束后再申请");
        }
        if (entity.getNum() == null) {
            throw new ValidateException("请输入售后数量");
        }
        if (entity.getType() != AfterSalesType.退货.ordinal() && entity.getType() != AfterSalesType.换货.ordinal()) {
            throw new ValidateException("售后类型不正确");
        }
        if (entity.getType() == AfterSalesType.退货.ordinal()) {
            if (orderEntity.getOrderStatus() == OrderStatus.已取消.getId() || orderEntity.getOrderStatus() == OrderStatus.已完成.getId() || orderEntity.getOrderStatus() == OrderStatus.待支付.getId()) {
                throw new ValidateException("该状态下不能申请退款/退货");
            }
            if (orderGoodsEntity.getBuyNum() < (orderGoodsEntity.getBackNum() + entity.getNum())) {
                throw new ValidateException("退货数量不能超过购买数量");
            }
        } else {
            if (orderEntity.getOrderStatus() != OrderStatus.已发货.ordinal()) {
                throw new ValidateException("该状态下不能申请换货");
            }
        }

        afterSales.getDb().begin();
        try {
            entity.setMemberId(RequestContext.getMemberId());
            entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
            entity.setOrderId(orderEntity.getId());
            entity.setOrderSn(orderEntity.getSn());
            entity.setStatus(AfterSalesStatus.待审核.ordinal());
            entity.setAmount(orderGoodsEntity.getShopPrice().multiply(new BigDecimal(entity.getNum())));
            entity.setStoreId(orderEntity.getStoreId());
            afterSales.save(entity);

            orderGoodsEntity.setInAfterSales(true);
            orderGoodsEntity.setAfterSalesStatus(AfterSalesStatus.待审核.ordinal());
            orderGoodsEntity.setAfterSalesType(entity.getType());
//            if(entity.getType() == AfterSalesType.退货.ordinal()) {
//                orderGoodsEntity.setBackNum(orderGoodsEntity.getBackNum() + entity.getNum());
//            }
            //orderGoodsEntity.setBakcAmount(null); 审核后加进来

            orderGoods.save(orderGoodsEntity);


            afterSales.getDb().commit();
        } catch (Exception ex) {
            afterSales.getDb().rollback();
            throw ex;
        }
    }

    @GetMapping("detail")
    public AfterSalesModel detail(@RequestParam Long id) throws SQLException {
        AfterSalesEntity entity = afterSales.entity(id);
        OrderGoodsEntity orderGoodsEntity = orderGoods.entity(entity.getOrderGoodsId());
        orderGoodsEntity.setGoodsImage(this.imageDomain + orderGoodsEntity.getGoodsImage());
        AfterSalesModel model = new AfterSalesModel(entity);

        OrderEntity orderEntity = order.entity(orderGoodsEntity.getOrderId());
        model.setOrderSn(orderEntity.getSn());
        StoreEntity storeEntity = store.entity(orderEntity.getStoreId());
        model.setStoreName(storeEntity.getName());
        model.setStoreLogoImageUrl(this.imageDomain + storeEntity.getLogoImageUrl());

        return model;
    }

    @GetMapping("list")
    public List<AfterSalesModel> list(@RequestParam(required = false) Integer status,
                                       @RequestParam(required = false) Integer pageIndex,
                                       @RequestParam(required = false) Integer pageSize) throws SQLException {

        String where = "member_id=" + RequestContext.getMemberId();
        if (status != null) {
            where += " and status=" + status;
        }
        PagerSetting setting = new PagerSetting();
        setting.setWhere(where);
        if (pageIndex != null) {
            setting.setPageIndex(pageIndex);
        }
        if (pageSize != null) {
            setting.setPageSize(pageSize);
        }
        List<AfterSalesEntity> afterSalesList = afterSales.list(setting);
        if(afterSalesList.size()==0){
            return new ArrayList<>();
        }

        List<OrderGoodsEntity> orderGoodsList = orderGoods.listByIds(afterSalesList.stream().map(t->t.getOrderGoodsId()).collect(Collectors.toList()));
       // List<OrderEntity> orderList = order.listByIds(afterSalesList.stream().map(t->t.getOrderId()).collect(Collectors.toList()));
        List<StoreEntity> storeList = this.store.listByIds(afterSalesList.stream().map(t->t.getStoreId()).distinct().collect(Collectors.toList()));
        List<AfterSalesModel> modelList = new ArrayList<>();

        for(AfterSalesEntity entity : afterSalesList){

            AfterSalesModel model = new AfterSalesModel(entity);
            Optional<OrderGoodsEntity> orderGoodsEntityOptional = orderGoodsList.stream().filter(t->t.getId().equals(entity.getOrderGoodsId())).findFirst();
            if(orderGoodsEntityOptional.isPresent()){
                OrderGoodsEntity orderGoodsEntity = orderGoodsEntityOptional.get();
                orderGoodsEntity.setGoodsImage(this.imageDomain + orderGoodsEntity.getGoodsImage());
                model.setOrderGoods(orderGoodsEntityOptional.get());
            }

//            Optional<OrderEntity> orderEntityOptional = orderList.stream().filter(t->t.getId().equals(entity.getOrderId())).findFirst();
//            if(orderEntityOptional.isPresent()){
//               model.setOrderSn(orderEntityOptional.get().getSn());
//            }

            Optional<StoreEntity> storeEntityOptional = storeList.stream().filter(t->t.getId().equals(entity.getStoreId())).findFirst();

            if(storeEntityOptional.isPresent()){
                model.setStoreName(storeEntityOptional.get().getName());
                model.setStoreLogoImageUrl(this.imageDomain + storeEntityOptional.get().getLogoImageUrl());
            }

            modelList.add(model);
        }
        return modelList;
    }

}
